package com.dean.scoket;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

public class DeanScokteClient {
    public void start(String username) throws IOException {
        Socket socket = new Socket();
        // 连接成功之后发送一条发送登录用户的信息给
        socket.connect(new InetSocketAddress("127.0.0.1",8080));
        DataOutputStream loginInfo = new DataOutputStream(socket.getOutputStream());
        DeanSocketMsg socketMsg = new DeanSocketMsg();
        socketMsg.setMsgType("LOGIN");
        socketMsg.setFromUser(username);
        ObjectMapper mapper = new ObjectMapper();
        String loginMsg = mapper.writeValueAsString(socketMsg);
        loginInfo.writeUTF(loginMsg);

        DataInputStream dis = new DataInputStream(socket.getInputStream());
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    String receiveMsg = null;
                    try {
                        receiveMsg = dis.readUTF();
                        DeanSocketMsg socketMsg = mapper.readValue(receiveMsg, DeanSocketMsg.class);
                        String fromUser = socketMsg.getFromUser();
                        String content = socketMsg.getContent();
                        System.out.println("["+fromUser+"]:"+content);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        Scanner scanner = new Scanner(System.in);
        DeanSocketMsg sendMsg = new DeanSocketMsg();
        sendMsg.setFromUser(username);
        sendMsg.setMsgType("TRANS");
        sendMsg.setTransFlag(false);
        while(true){
            String msg = scanner.nextLine();
            String toUser = msg.substring(0,5);
            String content = msg.substring(5);
            sendMsg.setToUser(toUser);
            sendMsg.setContent(content);
            dos.writeUTF(mapper.writeValueAsString(sendMsg));
        }
    }

    public static void main(String[] args) throws IOException {
        // 启动客户端
        DeanScokteClient client = new DeanScokteClient();
        client.start("dean2");
    }
}
